package com.cls.common.authentication;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.cls.common.entity.ResponseVO;
import com.cls.common.utils.MyUtil;
import com.cls.common.utils.StringUtils;
import com.cls.system.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author weimaomao
 * @date 2021/1/4
 */
public class SessionFilter  extends AccessControlFilter {

    /**
     * 是否允许访问
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        //Session未失效时验证通过
        if(null != currentUser || isLoginRequest(request, response)){
            return Boolean.TRUE;
        }
        //如果是ajax请求响应头会有，x-requested-with
        if(MyUtil.isAjax(request)){
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            //在响应头设置session状态
            httpServletResponse.setHeader("session-status", "timeout");
            httpServletResponse.setStatus(HttpStatus.HTTP_OK);
            ResponseVO failure = ResponseVO.failure(org.springframework.http.HttpStatus.UNAUTHORIZED, "登录超时！");
            JSON result = JSONUtil.parse(failure);
            ServletUtil.write(httpServletResponse,result.toJSONString(0), ContentType.JSON.getValue());
            //通过返回TRUE，通过前台的统一AJAX接受头部设置的sessionstatus参数，判断是否跳转到登录页面
            return Boolean.FALSE;
        }//FALSE  Session失效，切实非AJAX请求，验证是否，调用onAccessDenied跳转到登录页面
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //保存Request和Response 到登录后的链接
        saveRequestAndRedirectToLogin(request, response);
        return false;
    }


}